package com.guigu.qingcheng.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.guigu.qingcheng.service.OssService;
import com.guigu.qingcheng.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uplateFile(MultipartFile file) {
        // 从工具类中获取数据
        String endpoint= ConstantPropertiesUtils.END_POINT;
        String accessKeyId=ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret=ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName=ConstantPropertiesUtils.BUCKET_NAME;



        // 上传文件流
        try {
            // 创建OssClient实例
            OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            // 生成随机名称
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            originalFilename=uuid+originalFilename;

            // 拼接日期路径
            String time = new DateTime().toString("yyyy/MM/dd");
            originalFilename=time+"/"+originalFilename;

            // 上传
            ossClient.putObject(bucketName,originalFilename,inputStream);

            // https://education-10.oss-cn-beijing.aliyuncs.com/1.jpg
            // 拼接名称
            String url="https://"+bucketName+"."+endpoint+"/"+originalFilename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
